<?php

namespace app\controller;

use app\model\User;
use app\model\DrawRecord;
use support\Request;
use support\Response;

class UserController
{
    /**
     * 获取所有用户列表（单活动模式）
     */
    public function all(Request $request): Response
    {
        $users = User::all();
        return success($users);
    }

    /**
     * 根据参数获取对应用户列表
     */
    public function list(Request $request): Response
    {
        $page = $request->get('page', 1);
        $pagesize = $request->get('pagesize', 100);
        $isWinner = $request->get('is_winner');
        $order = $request->get('order', 'id');
        $random = $request->get('random', 0);

        // 根据参数构建查询条件
        $where = [];
        if ($isWinner !== null) {
            $where['is_winner'] = $isWinner;
        }

        $order = $random ? ['id' => 'RAND()'] : [$order => 'desc'];
        $result = User::getUserList($page, $pagesize, $where, $order);

        return success([
            'list' => $result['list'],
            'total' => $result['total'],
            'hasMore' => $result['hasMore']
        ]);
    }

    // 保存中奖用户信息并记录日志
    public function saveLucky(Request $request): Response
    {
        $data = json_decode($request->rawBody(), true);

        print_r($request->rawBody());
        if (!isset($data['id']) || !isset($data['users'])) {
            return json(['code' => 400, 'message' => '参数错误']);
        }

        if (!is_array($data['users'])) {
            return json(['code' => 400, 'message' => '用户参数错误']);
        }
        $userIds = $data['users'];
        foreach ($userIds as $userId) {
            $user = User::find($userId);
            if ($user) {
                $user->is_winner = 1;
                $user->prize_id = $data['id'];
                $user->round = (int) $data['round'];
                $user->save();
            }
            // 记录中奖用户日志到record
            DrawRecord::recordDraw($userId, $data['id'], (int) $data['round']);
        }

        return json([
            'code' => 0,
            'message' => '保存成功'
        ]);
    }

    /**
     * 获取已中奖用户列表
     */
    public function getWinners(Request $request): Response
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);

        $users = User::getWinners($page, $limit);

        return json([
            'code' => 0,
            'data' => $users
        ]);
    }

    /**
     * 创建用户
     */
    public function create(Request $request): Response
    {
        $data = $request->post();
        $user = User::create($data);

        return json([
            'code' => 0,
            'data' => $user
        ]);
    }

    /**
     * 更新用户
     */
    public function update(Request $request, int $id): Response
    {
        $data = $request->post();

        $user = User::find($id);
        if (!$user) {
            return json(['code' => 404, 'message' => '用户不存在']);
        }

        $user->save($data);

        return json([
            'code' => 0,
            'data' => $user
        ]);
    }

    /**
     * 删除用户
     */
    public function delete(Request $request, int $id): Response
    {
        $user = User::find($id);
        if (!$user) {
            return json(['code' => 404, 'message' => '用户不存在']);
        }

        $user->delete();

        return json(['code' => 0, 'message' => '删除成功']);
    }

    /**
     * 批量导入用户
     */
    public function batchCreate(Request $request): Response
    {
        $count = $request->get('count', 0);

        if ($count <= 0) {
            return json(['code' => 400, 'message' => '导入数量必须大于0']);
        }

        $result = User::batchCreate($count);

        return json([
            'code' => 0,
            'message' => '导入成功',
            'data' => ['count' => $result]
        ]);
    }

    /**
     * 清空所有用户
     */
    public function clearAll(Request $request): Response
    {
        User::clearAll();
        return json(['code' => 0, 'message' => '清空成功']);
    }
}
